package com.xixibaby.redis;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xixibaby.core.AuthException;
import com.xixibaby.core.SuperResponse;
import com.xixibaby.core.auth.AuthConstant;
import com.xixibaby.core.login.LoginInfoCacheVO;
import com.xixibaby.core.login.LoginInfoVO;
import com.xixibaby.core.Assert;
import com.zengtengpeng.operation.RedissonCollection;
import org.redisson.api.RMap;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.List;

/**
 * login.user(String sessionId);
 * login.user(Long userId)
 */
public class Login implements ApplicationContextAware {

    private static RedissonCollection redissonCollection;

    public static String user(LoginInfoVO loginInfo){
        return userCache(loginInfo).getLoginInfoUser();
    }

    private static LoginInfoCacheVO userCache(LoginInfoVO loginInfo){
        String cacheKey = StrUtil.format("{}:{}:{}", AuthConstant.AUTH_LOGIN_SESSION,loginInfo.getUserId(),loginInfo.getPlatform() );
        RMap<Object, Object> map = redissonCollection.getMap(cacheKey);
        if(map.isEmpty()){
            throw new AuthException();
        }
        return  Convert.convert(LoginInfoCacheVO.class, map);
    }

    public static List<String> authList(LoginInfoVO loginInfo){
        return userCache(loginInfo).getAdminAuths();
    }

    /**
     * 根据sessionId 获取登录用户信息
     * @param sessionId
     * @return
     */
    public static String user(String sessionId){
        LoginInfoVO loginInfoVO = LoginInfoVO.toVO(sessionId);
        return user(loginInfoVO);
    }

    public  static <T extends SuperResponse> T user(String sessionId, Class<T> clazz){
        LoginInfoVO loginInfoVO = LoginInfoVO.toVO(sessionId);
        String user = user(loginInfoVO);
        T result = JSONObject.parseObject(user, clazz);
        return  result;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        redissonCollection = applicationContext.getBean(RedissonCollection.class);
    }
}